<template>
  <div>
    <el-card>
      <el-form inline>
        <el-form-item label="角色搜索">
          <el-input v-model="SearchName" placeholder="请输入角色关键字搜索"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!SearchName" @click="search">搜索</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0;">
      <el-button type="primary" icon="Plus" @click="handleAddRole">添加角色</el-button>
      <el-table border style="margin: 10px 0;" :data="roleList">
        <el-table-column type="index" width="80px" align="center" label="#"></el-table-column>
        <el-table-column label="id" width="80px" align="center" prop="id"></el-table-column>
        <el-table-column label="角色名称" align="center" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime"></el-table-column>
        <el-table-column label="操作" align="center" width="300px">
          <template #="{ row }">
            <el-button type="primary" icon="User" size="small" @click="handleAssignPermission(row)">分配权限</el-button>
            <el-button type="warning" icon="Edit" size="small" @click="handleUpdateRole(row)">编辑</el-button>
            <el-popconfirm :title="`确定删除${row.roleName}?`" @confirm="deleteRole(row.id)" width="250px">
              <template #reference>
                <el-button type="danger" icon="Delete" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="currentPage"
                     v-model:page-size="pageSize"
                     :page-sizes="[5, 7, 9, 11]"
                     layout="prev, pager, next, jumper, ->, sizes, total"
                     :total="total"
                     @current-change="getAllRole"
                     @size-change="handlePageSizeChange" />
      <!-- 添加或修改角色 -->
      <el-dialog v-model="isShowAddOrUpdateRoleDialog" :title="roleParams.id ? '修改角色' : '添加角色'">
        <el-form :model="roleParams" :rules="rules" ref="formRef">
          <el-form-item label="职位名称" prop="roleName">
            <el-input v-model="roleParams.roleName" placeholder="请输入角色名称"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="isShowAddOrUpdateRoleDialog = false">取消</el-button>
          <el-button type="primary" @click="addOrUpdateRole">确定</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限 -->
      <el-drawer v-model="isShowAssignPermissionDrawer" title="分配菜单与按钮的权限">
        <!-- 树形控件 -->
        <el-tree ref="treeRef"
                 :data="permissionList"
                 show-checkbox
                 node-key="id"
                 default-expand-all
                 :default-checked-keys="selectIdList"
                 :props="defaultProps" />
        <template #footer>
          <div style="flex: auto">
            <el-button @click="isShowAssignPermissionDrawer = false">取消</el-button>
            <el-button type="primary" @click="handleSetPermission">确定</el-button>
          </div>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import useLayoutSettingStore from '@/store/modules/setting';
import { reqAddOrUpdateRole, reqAllPermissionById, reqAllRole, reqDeleteRoleById, reqSetPermission } from '@/api/acl/role';
import { AllPermissionResponseData, PermissionList, RoleData, RoleList } from '@/api/acl/role/type';
import { ElMessage } from 'element-plus';

const currentPage = ref<number>(1)
const pageSize = ref<number>(5)
const total = ref<number>(0)
const SearchName = ref<string>('')

const roleList = ref<RoleList>([])

const isShowAddOrUpdateRoleDialog = ref<boolean>(false)
const isShowAssignPermissionDrawer = ref<boolean>(false)

const formRef = ref()

const roleParams = ref<RoleData>({
  roleName: ''
})

const rules = {
  roleName: [{ required: true, min: 2, message: '角色名称至少两位', trigger: 'blur' }]
}

onMounted(() => {
  getAllRole()
})

// 分页查询角色列表
const getAllRole = async (pager = 1) => {
  currentPage.value = pager
  const result = await reqAllRole(currentPage.value, pageSize.value, SearchName.value)
  if (result.code === 200) {
    roleList.value = result.data.records
    total.value = result.data.total
  }
}

// 分页大小变化回调
const handlePageSizeChange = () => {
  getAllRole()
}

// 添加或更新角色
const addOrUpdateRole = async () => {
  await formRef.value.validate()
  const result: any = await reqAddOrUpdateRole(roleParams.value)
  if (result.code === 200) {
    ElMessage.success(roleParams.value.id ? '更新成功' : '添加成功')
    getAllRole(currentPage.value)
  } else {
    ElMessage.error(result.data)
  }
  isShowAddOrUpdateRoleDialog.value = false
}

const handleAddRole = () => {
  isShowAddOrUpdateRoleDialog.value = true
  Object.assign(roleParams.value, {
    id: 0,
    roleName: ''
  })
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

const handleUpdateRole = (row: RoleData) => {
  isShowAddOrUpdateRoleDialog.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
  Object.assign(roleParams.value, row)
}

// 删除角色
const deleteRole = async (id: number) => {
  const result: any = await reqDeleteRoleById(id)
  if (result.code === 200) {
    getAllRole(roleList.value.length > 1 ? currentPage.value : currentPage.value - 1)
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(result.data)
  }
}

const defaultProps = {
  children: 'children',
  label: 'name'
}

// 权限列表
const permissionList = ref<PermissionList>([])
// 已勾选权限的id列表
const selectIdList = ref<number[]>([])

// 分配权限按钮回调
const handleAssignPermission = async (row: RoleData) => {
  isShowAssignPermissionDrawer.value = true
  Object.assign(roleParams.value, row)
  const result: AllPermissionResponseData = await reqAllPermissionById(roleParams.value.id as number)
  if (result.code === 200) {
    permissionList.value = result.data
    selectIdList.value = filterSelectIdList(permissionList.value, [])
  }
}

// 过滤选中的权限id列表
const filterSelectIdList = (data: PermissionList, initArr: number[]) => {
  data.forEach(item => {
    if (item.level === 4 && item.select) {
      initArr.push(item.id)
    } else {
      filterSelectIdList(item.children as PermissionList, initArr)
    }
  })
  return initArr
}

// 树形控件
const treeRef = ref<any>()

// 提交权限
const handleSetPermission = async () => {
  // 参数准备
  // 获取角色id
  const roleId = roleParams.value.id
  // 获取所有全选和半选的id数组
  const permissionId = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()]
  const result: any = await reqSetPermission(roleId as number, permissionId)
  console.log(result)
  if (result.code === 200) {
    ElMessage.success('分配成功')
    isShowAssignPermissionDrawer.value = false
  } else {
    ElMessage.error(result.data)
    isShowAssignPermissionDrawer.value = false
  }
}

// 搜索功能
const search = () => {
  // 刷新列表
  getAllRole()
  // 清空搜索框
  SearchName.value = ''
}

// 重置功能
const reset = () => {
  const layoutSettingStore = useLayoutSettingStore()
  layoutSettingStore.toRefresh()
}
</script>

<style scoped></style>
